﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Practices.CompositeWeb.Interfaces;

namespace WCSFContrib.Extensions.Utility
{
	/// <summary>
	/// Event broking utilities
	/// </summary>
	public static class Utils
	{
		/// <summary>
		/// All types in the current loaded modules.
		/// </summary>
		/// <param name="moduleEnumerator">Module enumerator to get the module assembly names from.</param>
		/// <returns></returns>
		public static IEnumerable<Type> GetApplicationTypes(IModuleEnumerator moduleEnumerator)
		{
			Dictionary<string, Assembly> assemblies = GetCurrentAssemblies();
			foreach (IModuleInfo moduleInfo in moduleEnumerator.EnumerateModules())
			{
				Assembly assembly = assemblies[moduleInfo.AssemblyName];
				foreach (Type type in assembly.GetTypes())
				{
					yield return type;
				}
			}
		}

		/// <summary>
		/// All Assemblies in the current AppDomain as a dictionary.
		/// </summary>
		/// <returns>A Dictionary<assembly.fullName, assembly>.</returns>
		private static Dictionary<string, Assembly> GetCurrentAssemblies()
		{
			Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>();
			foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
				assemblies.Add(assembly.FullName.Split(',')[0], assembly);
			return assemblies;
		}
	}
}